package org.shj.netty.chartper5;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoClientHandler extends ChannelHandlerAdapter{
	
	private int counter;
	private String ECHO_REQ = "Hi, Li Xiao Long. Welcome to netty. $_";
	
	public EchoClientHandler(){
		
	}
	
	public void channelActive(ChannelHandlerContext ctx){
		for(int i = 0 ; i < 10; i++){
			
			ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
		}
			
	}
	
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
				
		String body = (String) msg;
		
		System.out.println("This is: " + (++counter) + " times return from server: "+ body);
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
}
